<?php

class Bootstrap extends Yaf_Bootstrap_Abstract
{
    private $config = null;

    public function _initSession($dispatcher)
    {
        date_default_timezone_set('PRC');
        Yaf_Session::getInstance()->start();
        define('REQUEST_METHOD', strtoupper($dispatcher->getRequest()->getMethod()));
    }

    public function _initConfig()
    {
        // 把配置保存起来
        $arrConfig = Yaf_Application::app()->getConfig();
        $this->config = $arrConfig;
        Yaf_Registry::set('config', $arrConfig);
    }

    public function _initLoader()
    {
        if (file_exists(APPLICATION_PATH . "/vendor/autoload.php")) Yaf_Loader::import(APPLICATION_PATH . "/vendor/autoload.php");
    }

    public function _initDb(Yaf_Dispatcher $dispatcher)
    {
        $db_config = ['default' => $this->config->database->default_connection];
        $connections = $this->config->database->connections;
        $connections = explode(',', $connections);
        foreach ($connections as $conn) {
            $_conn_conf = $this->config->database->get($conn);
            if (!is_null($_conn_conf)) {
                $dbusername = is_null($_conn_conf->username) ? $this->config->database->default_username : $_conn_conf->username;
                $dbpassword = is_null($_conn_conf->password) ? $this->config->database->default_password : $_conn_conf->password;

                $_ = explode(':', $_conn_conf->dsn);
                $db_config['connections'][$conn] = [
                    'type' => $_[0],
                    'dsn' => $_conn_conf->dsn,
                    'username' => $dbusername,
                    'password' => $dbpassword,
                    'fields_strict' => false,
                    'trigger_sql' => false,
                    'fields_cache' => true,
                    'schema_cache_path' => APPLICATION_PATH . '/cache/fields/',
                ];
            }
        }
        \think\facade\Db::setConfig($db_config);
    }

    public function _initPlugin(Yaf_Dispatcher $dispatcher)
    {
        // 注册一个插件
        // $objSamplePlugin = new SamplePlugin();
        // $dispatcher->registerPlugin($objSamplePlugin);
    }

    public function _initRoute(Yaf_Dispatcher $dispatcher)
    {
        // 在这里注册自己的路由协议,默认使用简单路由
    }

    public function _initView(Yaf_Dispatcher $dispatcher)
    {
        // 在这里注册自己的view控制器，例如smarty,firekylin
        if (REQUEST_METHOD != 'CLI') {
            $smarty = new SmartyAdapter(null, $this->config->smarty);
            $dispatcher->setView($smarty);
        }
    }
}
